#!/usr/bin/env python3
"""
安装AI模块依赖包的脚本
处理网络问题和逐个安装
"""
import subprocess
import sys
import os

def install_package(package, extra_args=None):
    """安装单个包，处理网络问题"""
    cmd = [sys.executable, "-m", "pip", "install", package]
    if extra_args:
        cmd.extend(extra_args)
    
    try:
        print(f"正在安装 {package}...")
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
        if result.returncode == 0:
            print(f"✓ {package} 安装成功")
            return True
        else:
            print(f"✗ {package} 安装失败: {result.stderr}")
            return False
    except Exception as e:
        print(f"✗ 安装 {package} 时出错: {e}")
        return False

def main():
    """主安装函数"""
    print("开始安装AI模块依赖包...")
    
    # AI核心依赖
    packages = [
        "openai>=1.7.0",
        "zhipuai>=2.0.1",
        "fastapi>=0.104.0",
        "uvicorn>=0.24.0",
        "pydantic>=2.5.0",
        "python-multipart>=0.0.6",
        "aiofiles>=23.2.0",
        "websockets>=12.0",
        "httpx>=0.25.0"
    ]
    
    # 安装参数
    install_args = ["--timeout", "30", "--retries", "3"]
    
    success_count = 0
    for package in packages:
        if install_package(package, install_args):
            success_count += 1
    
    print(f"\n安装完成: {success_count}/{len(packages)} 个包安装成功")
    
    if success_count == len(packages):
        print("所有AI依赖包安装成功！")
    else:
        print("部分包安装失败，请检查网络连接后重试")
        print("可以手动运行: pip install 包名")

if __name__ == "__main__":
    main()